// static/js/boot.js
// 🚀 星枢档案库 - 入口加载器
// 作用：统一加载所有资源，其他页面只需引入这一个文件

(function () {
    'use strict';

    // 📁 基础路径（可根据部署调整,从/static之后）
    const BASE_PATH = '';

    // 🧩 资源定义
    const ASSETS = {
        // --- CSS ---
        styles: [
            { id: 'common-css', href: `${BASE_PATH}/css/common.css` },
            { id: 'theme-css',  href: `${BASE_PATH}/css/theme/theme-cosmic.css` }
        ],

        // --- 核心 JS ---
        scripts: [
            { id: 'jquery',     src: `${BASE_PATH}/js/jquery-3.7.1.js` },
            { id: 'dom-js',  src: `${BASE_PATH}/js/components/dom.js` },
            { id: 'theme-js',   src: `${BASE_PATH}/js/components/theme-manager.js` },
            { id: 'query-js',   src: `${BASE_PATH}/js/components/QueryWrapper.js` }
        ],

        // --- HTML 组件 ---
        components: [
            { selector: '#header-placeholder',     url: `${BASE_PATH}/partials/header.html` },
            { selector: '#pagination-placeholder', url: `${BASE_PATH}/partials/pagination.html` }
        ]
    };

    // 🔧 工具函数：动态加载 CSS
    function loadCSS(href, id) {
        if (id && document.getElementById(id)) return Promise.resolve();

        return new Promise((resolve, reject) => {
            const link = document.createElement('link');
            link.id = id;
            link.rel = 'stylesheet';
            link.href = href;
            link.onload = () => resolve();
            link.onerror = () => reject(new Error(`CSS 加载失败: ${href}`));
            document.head.appendChild(link);
        });
    }

    // 🔧 工具函数：动态加载 JS
    function loadScript(src, id) {
        if (id && document.getElementById(id)) return Promise.resolve();

        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.id = id;
            script.src = src;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`JS 加载失败: ${src}`));
            document.head.appendChild(script);
        });
    }

    // 🔧 工具函数：加载 HTML 组件
    function loadComponent(selector, url) {
        return fetch(url)
            .then(res => {
                if (!res.ok) throw new Error(`组件加载失败: ${url}`);
                return res.text();
            })
            .then(html => {
                const el = document.querySelector(selector);
                if (el) el.outerHTML = html;
            });
    }

    // 🚀 启动加载流程
    function boot() {
        // 1. 先加载所有 CSS
        const cssPromises = ASSETS.styles.map(style => loadCSS(style.href, style.id));

        // 2. 再加载核心 JS（串行，保证顺序）
        const scriptPromise = Promise.all(cssPromises).then(() =>
            ASSETS.scripts.reduce(
                (chain, script) => chain.then(() => loadScript(script.src, script.id)),
                Promise.resolve()
            )
        );

        // 3. 加载组件（依赖 JS 已加载，比如 common.js 提供 $）
        const componentPromise = scriptPromise.then(() =>
            Promise.all(
                ASSETS.components.map(comp => loadComponent(comp.selector, comp.url))
            )
        );

        // 4. 返回主 Promise，便于后续操作
        return componentPromise;
    }

    // 🌟 暴露全局入口
    window.StarlightBoot = {
        start: boot,
        CONFIG: { BASE_PATH, ASSETS }
    };

    // 🔥 自动启动（可关闭）
    // 如果你希望自动执行，取消注释下一行
    document.readyState === 'loading' ?
        document.addEventListener('DOMContentLoaded', () => StarlightBoot.start()) :
        StarlightBoot.start();

})();